package com.unitd.springboot.starter.scheduler;

import com.unitd.scheduler.job.SchedulerFactoryBeanWrapper;
import com.unitd.scheduler.registry.IJobRegistry;
import com.unitd.scheduler.registry.impl.NullJobRegistry;
import com.unitd.scheduler.registry.impl.ZkJobRegistry;
import com.unitd.frame.comm.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

/**
 * @desc 指定frame-scheuler中 scheuler相关的配置信息
 * @filename ScheConfiguration.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2017/12/23
 */
@Configuration
@EnableConfigurationProperties(SchedulerProperties.class)
@ConditionalOnClass(SchedulerFactoryBeanWrapper.class)
@ConditionalOnProperty(name = "unitd.scheduler.groupName")
public class ScheConfiguration {

	@Autowired
	private SchedulerProperties cacheProperties;

	@Bean
	public IJobRegistry jobRegistry() {
		if (StringUtils.isNotBlank(cacheProperties.getRegistryServers())) {
			ZkJobRegistry registry = new ZkJobRegistry();
			registry.setZkServers(cacheProperties.getRegistryServers());
			return registry;
		} else {
			return new NullJobRegistry();
		}
	}

	@Bean
	@Order(Ordered.LOWEST_PRECEDENCE)
	public SchedulerFactoryBeanWrapper schedulerFactoryBean(IJobRegistry jobRegistry) {
		SchedulerFactoryBeanWrapper bean = new SchedulerFactoryBeanWrapper();
		bean.setGroupName(cacheProperties.getGroupName());
		bean.setThreadPoolSize(cacheProperties.getThreadPoolSize());
		bean.setRegistry(jobRegistry);
		bean.setScanPackages(cacheProperties.getScanPackages());
		return bean;
	}
}